package com.haibara.aioj.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.haibara.aioj.common.ErrorCode;
import com.haibara.aioj.exception.BusinessException;
import com.haibara.aioj.judge.codesandbox.CodeSandbox;
import com.haibara.aioj.judge.model.ExecuteCodeRequest;
import com.haibara.aioj.judge.model.ExecuteCodeRespond;
import org.apache.commons.lang3.StringUtils;

public class RemoteCodeSandbox implements CodeSandbox {

    private final static String AUTH_REQUEST_HEADER = "hai";
    private final static String AUTH_REQUEST_SECRET = "bara";

    @Override
    public ExecuteCodeRespond executeCode(ExecuteCodeRequest executeCodeRequest){
        System.out.println("远程代码沙箱");
        String url = "http://localhost:8090/codesandbox/execute";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER,AUTH_REQUEST_SECRET)
                .body(json)
                .execute()
                .body();
        if(StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"remote error");
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeRespond.class);
    }
}
